﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using ksyx;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Services;

namespace huaguwang
{
    public static class PageExp
    {
        public static ksyx.User.Model.T_UserExp GetUser(this Page page)
        {
            if (ksyx.User.Web.UserConst.GetUser(page) == null)
            {
                return null;
            }
            else
            {
                return ksyx.User.Web.UserConst.GetUser(page);
            }
        }

        public static void Exp_ToolBarErr(this ksyx.User.Web.WebUserToolBar.enumType e, System.Web.UI.Page page)
        {
            switch (e)
            {
                case ksyx.User.Web.WebUserToolBar.enumType.NoUser:
                    page.Response.Redirect("/yyhgroup/login.aspx");
                    page.Response.End();

                    break;
                case ksyx.User.Web.WebUserToolBar.enumType.NoPower:
                    page.Response.Write("用户没有权限");
                    page.Response.End();
                    break;
                case ksyx.User.Web.WebUserToolBar.enumType.Finish:
                    break;
                default:
                    page.Response.Write("工具条加载错误");
                    page.Response.End();
                    break;
            }

        }

        public static void Exp_PageAlter(this Page page, string ScriptMsg)
        {
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Exp_PageAlter", "alert('" + ScriptMsg + "');", true);
        }

        public static void Exp_PageAlterURL(this Page page, string ScriptMsg, string URL)
        {
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Exp_PageAlter", "alert('" + ScriptMsg + "');location.replace('" + URL + "');", true);
        }

        public static void Exp_PageAlterClose(this Page page, string ScriptMsg)
        {
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Exp_PageAlter", "alert('" + ScriptMsg + "');window.close();", true);
        }

        /// <summary>
        /// 统一日志填写
        /// </summary>
        /// <param name="strMsg">完整的提示信息/错误信息</param>
        /// <param name="FuncName">操作的结果和键值/方法名称</param>
        /// <param name="SubName">操作的描述/文件名称</param>
        /// <param name="IsOperate">true:操作日志  false:错误日志</param>
        public static void Exp_PageWriteLog(this Page page, string strMsg, string FuncName, string SubName, bool IsOperate)
        {
            //page.Exp_LogWrite_Exp(strMsg, SubName, FuncName, !IsOperate);
        }

        /// <summary>
        /// 统一日志填写
        /// </summary>
        /// <param name="page"></param>
        /// <param name="e">操作类型</param>
        /// <param name="FuncName">模块名称</param>
        /// <param name="id">操作内容ID</param>
        public static void Exp_PageWriteLog(this Page page, Log_Type e, string FuncName, int id)
        {
            var model = new M_T_MenterGroup_Log() 
            {
                AddDateTime = DateTime.Now,
                IP = page.Request.UserHostAddress,
                ModuleName = FuncName
            };
            var item = page.GetUser();
            if (item != null)
            {
                model.UserID = item.id;
            }
            else
            {
                return;
            }
            switch (e)
            {
                case Log_Type.delete:
                    model.FunctionName = FuncName + "删除";
                    model.Explain = "删除的资料ID:"+id;
                    break;
                case Log_Type.add:
                    model.FunctionName = FuncName + "添加";
                    model.Explain = "添加的资料ID:"+id;
                    break;
                case Log_Type.login:
                    model.FunctionName = FuncName + "登录";
                    model.Explain = "管理员ID："+id;
                    break;
                default:
                    model.FunctionName = FuncName + "编辑";
                    model.Explain = "编辑的资料id:" + id;
                    break;
            }

            var _dal = new D_T_MenterGroup_Log_Exp();

            _dal.Add(model);

        }
        /// <summary>
        /// 统一日志填写
        /// </summary>
        /// <param name="page"></param>
        /// <param name="e">操作类型</param>
        /// <param name="FuncName">模块名称</param>
        /// <param name="id">操作内容ID</param>
        public static void Exp_PageWriteLog(this Page page, Log_Type e, string FuncName, string deleteString)
        {
            var model = new M_T_MenterGroup_Log()
            {
                AddDateTime = DateTime.Now,
                IP = page.Request.UserHostAddress,
                ModuleName = FuncName
            };
            ksyx.User.Model.T_UserExp item = (ksyx.User.Model.T_UserExp)page.Session["UserItem"];
            if (item != null)
            {
                model.UserID = item.id;
            }
            else
            {
                return;
            }
            switch (e)
            {
                case Log_Type.delete:
                    model.FunctionName = FuncName + "删除";
                    model.Explain = "删除的资料id:" + deleteString;
                    break;
                case Log_Type.add:
                    model.FunctionName = FuncName + "添加";
                    model.Explain = "添加的资料id:" + deleteString;
                    break;
                default:
                    model.FunctionName = FuncName + "编辑";
                    model.Explain = "编辑的资料id:" + deleteString;
                    break;
            }

            var _dal = new D_T_MenterGroup_Log_Exp();

            _dal.Add(model);

        }

        /// <summary>
        /// 获取SKey
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static List<string> Exp_GetSKey(this Page page)
        {
            //SKey专门用来保存查询控件的值
            var Skey = page.Request.Params["SKey"];
            //分割字符串
            var sList = Skey.Exp_SplitToList('┆', S => S);
            return sList;
        }
        public static string Exp_SetSKey(this Page page, params string[] strText)
        {
            var strS = "";
            foreach (var item in strText)
            {
                strS += item.Replace("┆", "") + "┆";
            }
            return page.Server.UrlEncode(strS.Exp_Left(strS.Length - 1));
        }

        #region 图片上传方法相关
        /// <summary>
        /// 用于文件上传,图片只能是jpg和gif两种格式
        /// 文件最大大小，2M
        /// </summary>
        /// <param name="fuldFile">FileUpload对象控件</param>
        /// <param name="ReturnString">用于返回提示，若操作成功则返回文件名称如：aaa.jpg</param>
        /// <returns>上传的结果，true表示上传成功，false表示上传失败</returns>
        public static bool UpLoad(this Page page, FileUpload fuldFile, ref string ReturnString)
        {
            string filepath = "/upload/images/";
            var path = page.Server.MapPath(filepath);
            var fileSize = 2048000;
            Boolean fileOk = false;
            //判断是否已经选取文件
            if (fuldFile.HasFile)
            {
                //取得文件的扩展名,并转换成小写
                string fileExtension = System.IO.Path.GetExtension(fuldFile.FileName).ToLower();

                //文件名 ＝ 当前时间+3位随机数
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + GetRandCode(3);
                //缩略图文件名 ＝ 文件名+"_thumb"
                string fullName = fileName + fileExtension;//原图完整名称

                //限定只能上传jpg和gif图片
                string[] allowExtension = { ".jpg", ".gif", ".rar" };

                //rar时不保存文件后缀名
                string savePath = path + fullName;

                for (int i = 0; i < allowExtension.Length; i++)
                {
                    if (fileExtension == allowExtension[i])
                    {
                        fileOk = true;
                        break;
                    }
                }
                if (!fileOk)
                {
                    ReturnString = "上传文件的类型不合格，请重试";
                    return false;
                }

                if (fuldFile.PostedFile.ContentLength > fileSize)
                {
                    ReturnString = "文件大小超出规定大小，请重试";
                    return false;
                }

                try
                {
                    FileInfo fi = new FileInfo(savePath);
                    if (fi.Exists)
                    {
                        ReturnString = "已存在相同文件名的文件，请重试";
                        return false;
                    }
                    fuldFile.PostedFile.SaveAs(savePath);
                    ReturnString =filepath + fullName;
                    return true;
                }
                catch
                {
                    ReturnString = "数据异常，上传失败，请重试";
                    return false;
                }
            }
            ReturnString = "请先选择要上传的文件";
            return false;
        }

        /// <summary>
        /// 用于上传文件,上传图片时只能上传jpg和gif两种格式
        /// </summary>
        /// <param name="fuldFile">FileUpload对象控件</param>
        /// <param name="path">存放文件的父路径，不包括文件名</param>
        /// <param name="fileSize">文件的大小，以字节为单位如：1M＝1024000</param>
        /// <param name="ReturnString">用于返回提示，若操作成功则返回文件名称如：aaa.jpg</param>
        /// <returns>上传的结果，true表示上传成功，false表示上传失败</returns>
        public static bool UpLoad(this FileUpload fuldFile, string path, int fileSize, ref string ReturnString)
        {
            Boolean fileOk = false;
            //判断是否已经选取文件
            if (fuldFile.HasFile)
            {
                //取得文件的扩展名,并转换成小写
                string fileExtension = System.IO.Path.GetExtension(fuldFile.FileName).ToLower();

                //文件名 ＝ 当前时间+3位随机数
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + GetRandCode(3);
                //缩略图文件名 ＝ 文件名+"_thumb"
                string fullName = fileName + fileExtension;//原图完整名称

                //限定只能上传jpg和gif图片
                string[] allowExtension = { ".jpg", ".gif", ".rar" };

                //rar时不保存文件后缀名
                string savePath = path + fullName;

                for (int i = 0; i < allowExtension.Length; i++)
                {
                    if (fileExtension == allowExtension[i])
                    {
                        fileOk = true;
                        break;
                    }
                }
                if (!fileOk)
                {
                    ReturnString = "上传文件的类型不合格，请重试";
                    return false;
                }

                if (fuldFile.PostedFile.ContentLength > fileSize)
                {
                    ReturnString = "文件大小超出规定大小，请重试";
                    return false;
                }

                try
                {
                    FileInfo fi = new FileInfo(savePath);
                    if (fi.Exists)
                    {
                        ReturnString = "已存在相同文件名的文件，请重试";
                        return false;
                    }
                    fuldFile.PostedFile.SaveAs(savePath);
                    ReturnString = fullName;
                    return true;
                }
                catch
                {
                    ReturnString = "数据异常，上传失败，请重试";
                    return false;
                }
            }
            ReturnString = "请先选择要上传的文件";
            return false;
        }

        /// <summary>
        /// 用于上传文件,上传图片时只能上传jpg和gif两种格式
        /// </summary>
        /// <param name="fuldFile">FileUpload对象控件</param>
        /// <param name="path">存放文件的父路径，不包括文件名</param>
        /// <param name="fileSize">文件的大小，以字节为单位如：1M＝1024000</param>
        /// <param name="retStr">用于返回提示，若操作成功则返回文件名称如：aaa.jpg</param>
        /// <param name="IsCreateThumb">是否生成缩略图</param>
        /// <param name="thumSize">参数数组：专门用于上传图片时存放缩略图的宽和高,为空则说明不生成缩略图</param>
        /// <returns>上传的结果，true表示上传成功，false表示上传失败</returns>
        public static bool UpLoad(this FileUpload fuldFile, string path, int fileSize, ref List<string> retStr, bool IsCreateThumb, params int[] thumSize)
        {
            Boolean fileOk = false;
            //判断是否已经选取文件
            if (fuldFile.HasFile)
            {
                //取得文件的扩展名,并转换成小写
                string fileExtension = System.IO.Path.GetExtension(fuldFile.FileName).ToLower();

                //文件名 ＝ 当前时间+3位随机数
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + GetRandCode(3);
                //缩略图文件名 ＝ 文件名+"_thumb"
                string fullName = fileName + fileExtension;//原图完整名称
                string thumbName = fileName + "_thumb" + fileExtension;//缩略图文件完整名称

                //没有扩展名的文件名(.rar文件,其他文件不变)
                string saveName = (fileExtension == ".rar") ? System.IO.Path.GetFileNameWithoutExtension(fullName).ToLower() : fullName;

                //限定只能上传jpg和gif图片
                string[] allowExtension = { ".jpg", ".gif", ".rar" };

                //rar时不保存文件后缀名
                string savePath = path + saveName;

                for (int i = 0; i < allowExtension.Length; i++)
                {
                    if (fileExtension == allowExtension[i])
                    {
                        fileOk = true;
                        break;
                    }
                }
                if (!fileOk)
                {
                    retStr.Clear();
                    retStr.Add("上传文件的类型不合格，请重试");
                    return false;
                }

                if (fuldFile.PostedFile.ContentLength > fileSize)
                {
                    retStr.Clear();
                    retStr.Add("文件大小超出规定大小，请重试");
                    return false;
                }

                try
                {
                    FileInfo fi = new FileInfo(savePath);
                    if (fi.Exists)
                    {
                        retStr.Clear();
                        retStr.Add("已存在相同文件名的文件，请重试");
                        return false;
                    }
                    fuldFile.PostedFile.SaveAs(savePath);
                    retStr.Clear();
                    retStr.Add(fullName);
                    if (IsCreateThumb && fileExtension == ".jpg" || fileExtension == ".gif")
                    { //当上传图片时 要生成缩略图
                        if (thumSize.Length == 2)
                        {
                            CreateThumb(savePath, path + thumbName, thumSize);
                            retStr.Add(thumbName);
                            return true;
                        }
                    }
                    return true;
                }
                catch
                {
                    retStr.Clear();
                    retStr.Add("数据异常，上传失败，请重试");
                    return false;
                }
            }

            retStr.Clear();
            retStr.Add("请先选择要上传的文件");
            return false;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="srcPath">原图片路径</param>
        /// <param name="thumbPath">缩略图保存路径</param>
        /// <param name="thumSize">参数数组：专门用于上传图片时存放缩略图的宽和高</param>
        /// <returns></returns>
        private static bool CreateThumb(string srcPath, string thumbPath, params int[] thumSize)
        {
            try
            {
                Bitmap bmp = new Bitmap(srcPath);    //根据原始图片创建一张原始尺寸的缩略图
                System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack);
                int x = bmp.Width;
                int y = bmp.Height;

                if (thumSize.Length == 2)
                {
                    if (x > thumSize[0] || y > thumSize[1])
                    {
                        System.Drawing.Image aThumbanil = bmp.GetThumbnailImage(thumSize[0], thumSize[1], myCallBack, IntPtr.Zero);
                        aThumbanil.Save(thumbPath); //将生成的缩略图保存
                        aThumbanil.Dispose();       //释放文件流
                    }
                    else
                    {
                        bmp.Save(thumbPath);    //如过是小图片则直接保存
                    }
                }
                else
                {
                    float scale = (x > y) ? (x / 100F) : (y / 100F);
                    if (x > 120 || y > 90)
                    {
                        System.Drawing.Image aThumbanil = bmp.GetThumbnailImage((int)(x / scale), (int)(y / scale), myCallBack, IntPtr.Zero);
                        aThumbanil.Save(thumbPath); //将生成的缩略图保存
                        aThumbanil.Dispose();
                    }
                    else
                    {
                        bmp.Save(thumbPath);    //如过是小图片则直接保存
                    }
                }

                if (bmp != null)
                {
                    bmp.Dispose();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// CreateAThumbBmpImg方法需要回调函数
        /// </summary>
        /// <returns></returns>
        private static bool ThumbnailCallBack()
        {
            return false;
        }

        ///  <summary>
        ///  生成随机码
        ///  </summary>
        ///  <param  name="length">随机码个数</param>
        private static string GetRandCode(int length)
        {
            int rand;
            char code;
            string randomcode = String.Empty;

            //生成一定长度的验证码
            System.Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                rand = random.Next();

                if (rand % 3 == 0)
                {
                    code = (char)('A' + (char)(rand % 26));
                }
                else
                {
                    code = (char)('0' + (char)(rand % 10));
                }

                randomcode += code.ToString();
            }
            System.Web.HttpContext.Current.Session["CheckCode"] = randomcode;
            return randomcode;
        }
        #endregion

        /// <summary>
        /// 取出文本中的图片地址
        /// </summary>
        /// <param name="HTMLStr"></param>
        /// <returns></returns>
        public static string GetImgURL(string HTMLStr)
        {
            string str = string.Empty;
            //string sPattern = @"^<img\s+[^>]*>";
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>", RegexOptions.Compiled);
            Match m = r.Match(HTMLStr.ToLower());
            if (m.Success)
            {
                str = m.Result("${url}");
            }
            return str;
        }

        ///// <summary>
        ///// 用于判断类别名称是否重复 
        ///// </summary>
        //public static bool ClassExists(string name, int PetId, int id, Business_ClassType e)
        //{
        //    switch (e)
        //    { 
        //        case Business_ClassType.公司类别:
        //            var _cdal = new D_T_Business_ComClass();
        //            return _cdal.ExistsExp(name.Exp_Trim(), PetId, id);            
        //        case Business_ClassType.视频类别 :
        //            var _vdal = new D_T_Business_VideoClass();
        //            return _vdal.ExistsExp(name.Exp_Trim(), PetId, id);
        //        case Business_ClassType.新闻类别:
        //            var _ndal = new D_T_Business_IndexNewsClass();
        //            return _ndal.ExistsExp(name.Exp_Trim(), PetId, id);
        //        case Business_ClassType.产品类别:
        //            var _pdal = new D_T_Business_ProductClass();
        //            return _pdal.ExistsExp(name.Exp_Trim(), PetId, id);
        //        default: return false;
        //    }
        //}

        ///// <summary>
        ///// 用于判断类别名称是否重复 
        ///// </summary>
        //public static bool ClassExists(string name, int PetId, int id, Business_ContentType e)
        //{
        //    switch (e)
        //    {
        //        case Business_ContentType.公司信息:
        //            var _bdal = new D_T_Business_ComInfo();
        //            return _bdal.ExistsExp(name.Exp_Trim(), PetId, id);
        //        case Business_ContentType.产品信息:
        //            var _pdal = new D_T_Business_ProductInfo();
        //            return _pdal.ExistsExp(PetId, name.Exp_Trim(), id);
        //        case Business_ContentType.新闻信息:
        //            var _ndal = new D_T_Business_IndexNews();
        //            return _ndal.ExistsExp(PetId, name.Exp_Trim(), id);
        //        case Business_ContentType.用户信息:
        //            var _udal = new D_T_Business_UserInfo();
        //            return _udal.ExistsExp(name.Exp_Trim(), PetId, id);
        //        default: return false;
        //    }
        //}

        ///// <summary>
        ///// 用于判断当前结点是否为叶子结点 
        ///// </summary>
        //public static bool RootNotes(int PetId, Business_ClassType e)
        //{
        //    switch (e)
        //    { 
        //        case Business_ClassType.公司类别:
        //            var _cdal = new D_T_Business_ComClass();
        //            return _cdal.HasChildNodes(PetId);
        //        case Business_ClassType.视频类别:
        //            var _vdal = new D_T_Business_VideoClass();
        //            return _vdal.HasChildNodes(PetId);
        //        case Business_ClassType.新闻类别:
        //            var _ndal = new D_T_Business_IndexNewsClass();
        //            return _ndal.HasChildNodes(PetId);
        //        case Business_ClassType.产品类别:
        //            var _pdal = new D_T_Business_ProductClass();
        //            return _pdal.HasChildNodes(PetId);
        //        default: return false;
        //    }
        //}
    }

    /// <summary>
    /// 写日志的类型
    /// </summary>
    public enum Log_Type
    { 
        add,
        delete, 
        login,
        update
    }
    
     
    /// <summary>
    /// JavaScript常用方法alert;
    /// </summary>
    public static class ScriptHelper
    {
        const string SCROPTSTR = "<script type='text/javascript'>{0}</script>";
        /// <summary>
        /// 获取javascript代码
        /// </summary>
        public static string Exp_GetScript(this Page page, string innerCode)
        {
            return string.Format(SCROPTSTR, innerCode);
        }

        /// <summary>
        /// 获取弹出窗口内容
        /// </summary>
        public static string Exp_GetAlert(this Page page, string alertContent)
        {
            string innerCode = string.Format("alert('{0}');", alertContent);
            return string.Format(SCROPTSTR, innerCode);
        }

        /// <summary>
        /// 弹出窗口并跳转页面
        /// </summary>
        public static void Exp_AlertAndGo(this Page page, string alertContent, string url, bool isParentGo)
        {
            string tmp = string.Empty;
            string innerCode = string.Empty;
            if (isParentGo)
            {
                innerCode = "alert('{0}');window.parent.location='{1}';";
            }
            else
            {
                innerCode = "alert('{0}');window.location='{1}';";
            }
            innerCode = string.Format(innerCode, alertContent, url);
            tmp = Exp_GetScript(page, innerCode);
            HttpContext.Current.Response.Write(tmp);
            HttpContext.Current.Response.End();
        }

        public static void Exp_AlertAndGo(this Page page, string alertContent, string url)
        {
            Exp_AlertAndGo(page, alertContent, url, false);
        }

        /// <summary>
        /// 弹出窗口并返回
        /// </summary>
        public static void Exp_AlertAndGoBack(this Page page, string alertContent)
        {
            string innerCode = string.Format("alert('{0}');history.back();", alertContent);
            HttpContext.Current.Response.Write(Exp_GetScript(page, innerCode));
            HttpContext.Current.Response.End();
        }
    }
}
